<?php

namespace control;

/*
*凭证模板类
*/

class voucherModelClass extends adIndexClass
{
    private const page    = 'voucherModel';
    private const table   = 'voucher';
    private const tableMx = 'voucher_detail';
    private const title   = '凭证模板';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "凭证字"  => idSelect(array('name' => 'voucherWordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word')),
                    '制单人'  => selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    '摘要' => text(array("name" => "summary")),
                    "备注" => text(array("name" => "text")),
                    '科目' => componentClass::subjectSelect(),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "text"    => $this->post('text'),//备注
            "summary" => $this->post('summary'),
        );
        //全等查询数组
        $equal = array(
            'voucherWordId' => $this->post('voucherWordId'),
            'stid'          => $this->post('stid'),
            'coid'          => self::$coid,
            'isTemplate'    => '是'
        );
        $and   = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        if ($this->post('summary')) {
            $and .= " and id in (select orderId from " . self::tableMx . " where coid = '" . self::$coid . "' and summary like '%" . $this->post('summary') . "%')";
        }
        if ($this->post('subjectId')) {
            $and .= " and id in (select orderId from " . self::tableMx . " where coid = '" . self::$coid . "' and subjectId = '" . $this->post('subjectId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => "recordDate desc,time desc"));
        $url   = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        //获取表头
        //获取记录
        $html = <<<eof
<div class="voucher-body">
    <div class='voucher-title'><div class='td-title' style="width: 50px"><input class="checked_box" type="checkbox" form="listForm" name="listId" onchange="checkAll(this)"></div><div class='td-title' style='width: 214px'></span>摘要</div><div class='td-title' style='width: 446px'>科目</div><div class='td-title' style='width: 104px;text-align: right'>借方金额</div><div class='td-title' style='width: 104px;text-align: right'>贷方金额</div><div style="text-align: right">操作</div></div>
    <div class="voucher-list">
eof;

        foreach ($page['array'] as $array) {
            $html     .= <<<eof
<div class="voucher-list-item">
    <div class="voucher-list-line">
        <div class="inlie-block" style="width: 50px"><input class="checked_box" type="checkbox"  name="listId[]" value="$array[id]"></div><div class="inlie-block" style="width: 214px;color: #999999">模板类型：{$array['templateType']}</div><div class="inlie-block" style="color: #999999">模板名称：$array[templateName]</div>
        <span class="del-row-button right mlf" onclick="layer('voucherModel','operate',{act:'del',id:'{$array['id']}'})">删除</span><span class="del-row-button right mlf" onclick="newIframe('录凭证','{$url}&id={$array['id']}')">编辑</span>
    </div>
    <div class="voucher-list-lines">

eof;
            $all      = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]' order by list asc"));
            $jieTotal = $daiTotal = 0;
            foreach ($all['array'] as $val) {
                $jieMoney = $val['direction'] == '借' ? self::centToYuan($val['money']) : 0;
                $daiMoney = $val['direction'] == '贷' ? self::centToYuan($val['money']) : 0;
                $jieTotal += $jieMoney;
                $daiTotal += $daiMoney;
                $html     .= <<<eof
<div class="voucher-list-line">
<div style="width: 50px"></div><div style="width: 214px">{$val['summary']}</div><div style="width: 446px">{$val['subjectCode']}{$val['subjectName']}</div><div style="width: 104px;text-align: right">{$jieMoney}</div><div style="width: 104px;text-align: right">{$daiMoney}</div></div>
eof;

            }
            $daxie = voucherEditClass::num_to_rmb($jieTotal);
            $html  .= <<<eof
<div class="voucher-list-line">
<div style="width: 50px"></div><div style="width: 214px">合计：$daxie</div><div style="width: 446px"></div><div style="width: 104px;text-align: right">{$jieTotal}</div><div style="width: 104px;text-align: right">{$daiTotal}</div></div>
</div></div>
eof;
        }
        if (is_array($page['array']) && count($page['array']) == 0) {
            $html .= <<<eof
<div class="voucher-list-item">
    <div class="voucher-list-line" style="text-align: center">
        一条数据都没有
    </div>
    <div class="voucher-list-lines">

eof;
        }
        $html .= "</div></div>";
        $html .= $this->style() . $this->js();

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . clear . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.mlf{margin-left: 20px}
.voucher-list-head{height: 40px;line-height: 40px}
.voucher-list-item{padding: 10px 5px;border-bottom: 1px solid rgba(215, 215, 215, 1);}
.voucher-list-line{line-height: 40px;height: 40px}
.voucher-list-line>div{display: inline-block}
.inlie-block{display: inline-block}
.voucher-list{width: calc(100% - 20px);margin: 0 auto}
.checked_box{width: 15px;height: 15px}
.voucher-title .td-title{float: left;}
.voucher-title{padding: 0 5px;background-color: rgba(248, 248, 248, 1);box-sizing: border-box;height: 34px;line-height: 34px;border-bottom: 1px solid rgba(215, 215, 215, 1);margin: 0 auto;width: calc(100% - 20px)}
</style>
eof;

    }

    private function js(): string
    {
        return <<<eof
<script>
</script>
eof;

    }


    public function detail()
    {
        //返回
        return $this->room();
    }

    /**
     * 记账凭证
     * @return string
     */
    public function room(): string
    {

        $voucherEdit   = new voucherEditClass();
        $shortcutImg   = $voucherEdit->shortcutImg . '?v=' . version;
        $printIco      = $voucherEdit->printIcon . '?v=' . version;
        $dataTr        = '';//凭证行内容
        $jieTotalMoney = $daiTotalMoney = 0;//借方和贷方金额总计
        //为template时表示使用模板创建数据，为model是表示模板编辑,为salary标识从工资创建凭证,为redChong:红冲 insert:插入
        $method                   = $this->get('method');
        $id                       = $this->get('id') ?: suiji();
        $info                     = query(self::table, "id = '$id'");
        $voucherWord              = query('voucher_word', "id = '$info[voucherWordId]'");
        $redClass                 = '';//红冲时标红
        $source                   = $method ? $voucherEdit->typeOption[$method] : '正常';//来源类型
        $sourceId                 = '';//来源ID,红冲时需要知道是哪张凭证的红冲
        $lastVoucher              = query(self::table, "coid = '" . self::$coid . "' order by time desc ");
        $defaultVoucherWord       = query('voucher_word', "coid = '" . self::$coid . "' and isDefault = '是'");
        $defaultVoucherWord['id'] = $lastVoucher['id'] ? $lastVoucher['voucherWordId'] : $defaultVoucherWord['id'];
        $fixDate                  = $voucherEdit->voucherSetting('fixDate');
        if ($fixDate == '是' && empty($info['id'])) {
            $info['recordDate'] = $voucherEdit->voucherSetting('fixDateValue');
        }
        //编辑模板
        $templateSelect = select(array('name' => 'templateType', 'class' => 'template-input template-select', 'title' => '请选择', 'option' => explode('，', para('voucherTemplateType')), 'value' => $info['templateType']));


        $col_list = 0;//行号
        if ($info['id']) {
            $all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by rowList,list asc"));
            foreach ($all['array'] as $array) {
                $col_list++;
                //模板
                $mxId           = suiji();
                $subjectAttr    = json_decode($array['subjectAttr'], true);
                $subject        = query('subject', "id = '$array[subjectId]'");
                $jieMoney       = $array['direction'] == '借' ? self::centToYuan($array['money']) : 0;
                $daiMoney       = $array['direction'] == '贷' ? self::centToYuan($array['money']) : 0;
                $jieMoneyText   = self::yuanToCent($jieMoney) ?: '';
                $daiMoneyText   = self::yuanToCent($daiMoney) ?: '';
                $currency       = query('currency', "id = '$array[currencyId]'");
                $numAccountHide = 'hide';
                if ($subject['numAccount'] == '是') {
                    $numAccountHide = '';
                }
                $assistName    = '';
                if ($subject['assistAccount'] == '是') {
                    if (!empty($array['khid'])) {
                        $kehu       = query('kehu', "khid = '$array[khid]'");
                        $assistName .= '_' . $kehu['orderNo'] . $kehu['companyName'];
                    }
                    if (!empty($array['supplierId'])) {
                        $supplier   = query('supplier', "id = '$array[supplierId]'");
                        $assistName .= '_' . $supplier['code'] . $supplier['name'];
                    }
                    if (!empty($array['staffId'])) {
                        $staff      = query('staff', "stid = '$array[staffId]'");
                        $assistName .= '_' . $staff['orderNo'] . $staff['name'];
                    }
                    if (!empty($array['departmentId'])) {
                        $department = query('department', "id = '$array[departmentId]'");
                        $assistName .= '_' . $department['name'];
                    }
                    if (!empty($array['materialId'])) {
                        $assistName .= '_' . materialClass::getName($array['materialId'], '');
                    }
                    if (!empty($array['projectId'])) {
                        $project    = query('project', "id = '$array[projectId]'");
                        $assistName .= '_' . $project['orderNo'] . $project['name'];
                    }
                    if (!empty($array['cashId'])) {
                        $cash       = query('cash', "id = '$array[cashId]'");
                        $assistName .= '_' . $cash['code'] . $cash['name'];
                    }
                }
                $currencyAccount = 'hide';
                if ($subject['currencyAccount'] == '是') {
                    $currencyAccount = '';
                }
                $jieTotalMoney               += $jieMoney;
                $daiTotalMoney               += $daiMoney;
                $subject['name']             = subjectClass::getName($subject['id']);
                $array['voucherNum']         = voucherEditClass::formatZero($array['voucherNum']);
                $subjectAttr['voucherPrice'] = voucherEditClass::formatZero($subjectAttr['voucherPrice'], 2) ?? '';
                $jieMoneyText                = voucherEditClass::splitNumber($jieMoneyText);
                $daiMoneyText                = voucherEditClass::splitNumber($daiMoneyText);
                $dataTr                      .= <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span>$col_list</span></div>
    <div class="cell oprate-col">
            <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$voucherEdit->copyIcon}">
            <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$voucherEdit->addIco}">
            <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$voucherEdit->delIco}"> 
    </div>
    <div class="cell summary-col">
        <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
        <div class="summary">{$array['summary']}</div>
        <textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">{$array['summary']}</textarea>
    </div>
    <div class="cell subject-col">
          <div class="subject-input-parent">
                <textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea>
          </div>
          <div class="subject-content subject-text" data-asset="{$array['idCollection']}">
                <div class="subject-name">{$array['subjectCode']} {$subject['name']}$assistName</div>
                <input type="hidden" name="subjectId[$mxId]" value="$array[subjectId]">
                <input type="hidden" name="khid[$mxId]" value="$array[khid]">
                <input type="hidden" name="supplierId[$mxId]" value="$array[supplierId]">
                <input type="hidden" name="staffId[$mxId]" value="$array[staffId]">
                <input type="hidden" name="projectId[$mxId]" value="$array[projectId]">
                <input type="hidden" name="materialId[$mxId]" value="$array[materialId]">
                <input type="hidden" name="cashId[$mxId]" value="$array[cashId]">
                <input type="hidden" name="departmentId[$mxId]" value="$array[departmentId]">
          </div>
    </div>
    <div class="cell num-col">
          <div class="num-name $numAccountHide">
              <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">{$array['voucherNum']}</span><input name="voucherNum[$mxId]" type="hidden" value="{$array['voucherNum']}"></div>
              <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">{$subjectAttr['voucherPrice']}</span><input  name="voucherPrice[$mxId]" type="hidden" value="{$subjectAttr['voucherPrice']}"></div>
          </div>
          <div class="currency-name $currencyAccount">
              <div><span class="voucher-money-btn">{$currency['code']}：</span><span class="voucher-money-text">{$subjectAttr['voucherMoney']}</span><input name="voucherMoney[$mxId]" type="hidden" value="{$subjectAttr['voucherMoney']}"><input name="currencyId[$mxId]" type="hidden" value="{$array['currencyId']}"></div>
              <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">{$array['rate']}</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value="{$array['rate']}"></div>
          </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
            <div class="jie-text $redClass format-line-box">
                $jieMoneyText
            </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"   value="$jieMoney">
    </div>
   <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text $redClass format-line-box">$daiMoneyText</div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="$daiMoney">
   </div></div>
eof;
            }
        }

        $all['array'] = $all['array'] ?? [];
        $num          = 12 - count($all['array']);
        for ($i = 1; $i <= $num; $i++) {
            $col_list++;
            $mxId   = suiji();
            $dataTr .= <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span>$col_list</span></div>
    <div class="cell oprate-col">
            <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$voucherEdit->copyIcon}">
            <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$voucherEdit->addIco}">
            <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$voucherEdit->delIco}"> 
    </div>
    <div class="cell summary-col">
            <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
            <div class="summary"></div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220"></textarea>
    </div>
    <div class="cell subject-col">
        <div class="subject-input-parent"><textarea class="subject-input hide hide-input" type="text" maxlength="220"></textarea></div>
        <div class="subject-content subject-text">
            <div class="subject-name"></div>
            <div class="balance hide">
                余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
            </div>
            <input type="hidden" name="subjectId[$mxId]" value="">
            <input type="hidden" name="khid[$mxId]" value="">
            <input type="hidden" name="supplierId[$mxId]" value="">
            <input type="hidden" name="staffId[$mxId]" value="">
            <input type="hidden" name="projectId[$mxId]" value="">
            <input type="hidden" name="materialId[$mxId]" value="">
            <input type="hidden" name="cashId[$mxId]" value="">
            <input type="hidden" name="departmentId[$mxId]">
        </div>
    </div>
    <div class="cell num-col">
        <div class="num-name hide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name hide">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
        <div class="jie-text format-line-box">
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line l-blue"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line l-blue"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line pink"></div>
            <div class="format-line"></div>
        </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"   value="">
    </div>
    <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text format-line-box">
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line l-blue"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line l-blue"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line pink"></div>
                <div class="format-line"></div>
            </div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="">
    </div>
</div>
eof;
        }
        $jieTotalMoney = round($jieTotalMoney, 2);
        $daiTotalMoney = round($daiTotalMoney, 2);
        $jieTotalMoney = self::yuanToCent($jieTotalMoney);
        $daiTotalMoney = self::yuanToCent($daiTotalMoney);
        $moneyCn       = voucherEditClass::num_to_rmb(self::centToYuan($jieTotalMoney));
        $jieTotalMoney = voucherClass::zeroToEmpty($jieTotalMoney);
        $daiTotalMoney = voucherClass::zeroToEmpty($daiTotalMoney);
        $staffName     = !$info['id'] ? $this->control['name'] : self::findStaff($info['stid']);

        $info['voucherNo'] = $info['voucherNo'] ?: 1;
        $saveBtn           = <<<eof
<span class="spanButton li-btn-blue-bg marginl0" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=voucherModel&fun=templateEdit')">保存</span>
eof;
        //反算规则
        $rateAndMoney = $voucherEdit->voucherSetting('rateAndMoney') ?: 'money';
        $numAndPrice  = $voucherEdit->voucherSetting('numAndPrice') ?: 'price';
        //更多按钮
        $printButton = '';
        if ($info['id']) {
            $printButton = "<img alt='打印凭证' title='打印凭证' src='" . $printIco . "' onclick=\"window.open(root+'control/adIndex.html?cla=voucherEdit&fun=printPage&id={$info['id']}')\" />";
        }
        //快捷键按钮
        $voucherEdit->keyboardIcon = $voucherEdit->keyboardIcon . '?v=' . version;
        $shortCutButton            = <<<eof
 <div class="shortcut-key"  id="shortKey">
    <img alt="点击查看快捷键" title="点击查看快捷键" src="{$voucherEdit->keyboardIcon}"/>
   
    <div class="shortcut-key-content">
     <div class="arrow"></div>
        <div><p>键盘常用操作</p></div>
        <div class="shortcut-img"><img alt=""  src="$shortcutImg" /></div>
        <div class="shortcut-table">
            <table class="tableMany">
            <thead><tr><td>凭证</td><td>快捷键</td></tr></thead>
            <tbody>
                <tr><td>保存并新增</td><td>F12</td></tr>
                <tr><td>保存</td><td>Ctrl+S</td></tr>
                <tr><td>新增</td><td>Alt+N</td></tr>
                <tr><td>录入第二条分录</td><td>Enter</td></tr>
                <tr><td>自动平衡借贷方金额</td><td>=</td></tr>
            </tbody>
            </table>
        </div>
    </div>
    </div>
eof;
        $data['html']              = <<<efo
<form name="voucherForm">
<div class="voucher-body">
<div class="subject-selector hide">
            <div class="subject-tabs">
                <div class="tab-item active">全部</div>
                <div class="tab-item">资产</div>
                <div class="tab-item">负债</div>
                <div class="tab-item">权益</div>
                <div class="tab-item">成本</div>
                <div class="tab-item">损益</div>
            </div>
            <div class="subject-box"></div>
            <div onclick="addSubject()"  title="添加科目" class="add_subject_button del-row-button">+添加</div>
</div>
<div class="currency-assit">
     <div class="currency-assit-ul"></div>
     <div class="auxiliary-accounting-button">
        <input type="button" value="取消" onclick="hideCurrency()">
        <input type="button" value="确定" onclick="confirmCurrency()" class="confirm-button">
    </div>
</div>
<div class="calendarBody" data-r="$rateAndMoney" data-n="$numAndPrice">
<div class="voucher-flex-container">
    <div class="container-header">
        <div class="cell center setting-col"><img onclick="layer('voucherEdit', 'voucherNumAdd', {})" alt="设置" title="设置" style="cursor: pointer" src="{$voucherEdit->settingIcon}"></div>
        <div class="cell oprate-col">$shortCutButton</div>
        <div class="cell summary-col">摘要</div>
        <div class="cell subject-col">科目</div>
        <div class="cell num-col">数量/外币</div>
        <div class="cell jie-col">
            <div class="center">借方金额</div>
                <div class="moneyUnit format-line-box">
                    <div class="format-line">亿</div>
                    <div class="format-line">千</div>
                    <div class="format-line">百</div>
                    <div class="format-line l-blue">十</div>
                    <div class="format-line">万</div>
                    <div class="format-line">千</div>
                    <div class="format-line l-blue">百</div>
                    <div class="format-line">十</div>
                    <div class="format-line">元</div>
                    <div class="format-line pink">角</div>
                    <div class="format-line">分</div>
                </div>
        </div>
        <div class="cell dai-col">
             <div class="center">贷方金额</div>
             <div class="moneyUnit format-line-box">
                    <div class="format-line">亿</div>
                    <div class="format-line">千</div>
                    <div class="format-line">百</div>
                    <div class="format-line l-blue">十</div>
                    <div class="format-line">万</div>
                    <div class="format-line">千</div>
                    <div class="format-line l-blue">百</div>
                    <div class="format-line">十</div>
                    <div class="format-line">元</div>
                    <div class="format-line pink">角</div>
                    <div class="format-line">分</div>
             </div>
        </div>
        <div class="scroll-bar-col"></div>
    </div>
    <div class="container-body" id="container-body">
            $dataTr
    </div>
    <div class="container-foot">
        <div class="container-body-row">
            <div class="cell center heji-col"><div class="upper-money-total">合计：<span>{$moneyCn}</span></div></div>
            <div class="cell jie-col">
              <div class="show_text show_money">
                  <div class="jie-text jie-total $redClass format-line-box">
                    $jieTotalMoney
                </div>
              </div>
            </div>
            <div class="cell dai-col">
                <div class="show_text show_money">
                    <div class="dai-text dai-total $redClass format-line-box">
                        $daiTotalMoney
                    </div>
                </div>
            </div>
            <div class="scroll-bar-col"></div>
        </div>
    </div>
    <div class="voucher-button container-tail">
         <div><span style="">制单人：{$staffName}</span></div>
         <div class="voucher-button">模板名称：<input name="templateName" class="template-input" value="{$info['templateName']}">&emsp;模板类型：$templateSelect</div>
         <div>
            $saveBtn
         </div>
    </div>
</div>
<div>
    <input name="id" value="$id" type="hidden">
    <input name="sourceId" value="$sourceId" type="hidden">
    <input type="hidden" name="source" value="$source">
    <div id="file-list" class="hide file-list"></div>    
</div>
</div>
</div>
</form>
efo;
        $data['html']              = $voucherEdit->css() . $data['html'];
        $data['html']              .= $voucherEdit->js();
        //返回
        return $this->tab($data);
    }

    /**
     * 编辑
     */
    public function templateEdit()
    {
        $from          = $this->get('from');
        $voucherEdit   = new voucherEditClass();
        $id            = $this->post('id') ?: self::getId();
        $subjectIds    = $this->post('subjectId');
        $cashIds       = $this->post('cashId');
        $khids         = $this->post('khid') ?: [];
        $supplierIds   = $this->post('supplierId') ?: [];
        $staffIds      = $this->post('staffId') ?: [];
        $projectIds    = $this->post('projectId') ?: [];
        $departmentIds = $this->post('departmentId') ?: [];
        $materialIds   = $this->post('materialId') ?: [];
        $voucherNums   = $this->post('voucherNum') ?: [];
        $voucherPrices = $this->post('voucherPrice') ?: [];
        $voucherRates  = $this->post('voucherRate') ?: [];
        $jieMoneys     = $this->post('jieMoney');
        $daiMoneys     = $this->post('daiMoney');
        $summarys      = $this->post('summary');
        $mxIds         = $this->post('mxId');
        $currencyIds   = $this->post('currencyId');
        $sourceId      = $this->post('sourceId');//来源ID
        $isSaveMoney   = (bool)$this->post('isSaveMoney');
        $field         = [
            'recordDate'    => $this->post('recordDate'),
            'voucherWordId' => $this->post('voucherWordId'),
            'receiptNum'    => $this->post('receiptNum'),
            'templateName'  => $this->post('templateName'),
            'templateType'  => $this->post('templateType'),
            'voucherNo'     => $this->post('voucherNo'),
            'text'          => $this->post('text'),
        ];
        $annotation    = [
            'templateName' => '模板名称',
            'templateType' => '模板类型',
        ];
        $rules         = [
            'templateName' => 'required',
            'templateType' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = '请填写凭证内容';
        } elseif (count(array_filter($subjectIds)) < 2) {
            $json['warn'] = '该凭证存为模板需至少两行分录';
        } elseif (empty(array_filter($subjectIds))) {
            $json['warn'] = '请选择科目';
        } elseif (empty($field['templateType'])) {
            $json['warn'] = '请选择模板类型';
        } elseif (empty($field['templateName'])) {
            $json['warn'] = '请填写模板名称';
        } elseif (self::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and isTemplate = '是' and templateType = '$field[templateType]' and templateName = '$field[templateName]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此名称的模板';
        } elseif ($isSaveMoney && round(array_sum($jieMoneys), 2) != round(array_sum($daiMoneys), 2)) {
            $json['warn'] = '借贷金额不相等';
        } elseif ($isSaveMoney && count(array_filter($subjectIds)) != count(array_filter($jieMoneys)) + count(array_filter($daiMoneys))) {
            $json['warn'] = '科目或金额未填写完成';
        } else {
            $this->startTrans();
            $company = query('company', "coid = '" . self::$coid . "'");
            if ($company['isAudit']) {
                $field['workFlow'] = '待审核';
            } else {
                $field['workFlow']   = '已记账';
                $field['auditStid']  = $company['auditStid'];
                $field['recordStid'] = $company['managerId'];
            }
            if (!$info['id']) {
                $field['sourceId'] = $sourceId;
                $field             = array_merge($field, [
                    'id'         => $id,
                    'coid'       => self::$coid,
                    'isTemplate' => '是',
                    'stid'       => self::$stid,
                    'templateNo' => self::generateTemplateNo(),
                ]);
                $json['warn']      = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            $totalMoney = 0;
            $ids        = [];
            foreach ($mxIds as $k => $mxId) {
                $mId = $mxId;
                if ($from == 'new') {
                    //存为模板时
                    $mId = suiji();
                }
                $index  = $k + 1;
                $detail = query(self::tableMx, "id = '$mId'");
                if ($subjectIds[$mxId]) {
                    $subject = query('subject', "id = '$subjectIds[$mxId]'");
                    $ids[]   = $mId;
                    $bool    = $voucherEdit->assistAccountJuage($subject, $index, $mxId, [
                        'khid'         => $khids,
                        'supplierId'   => $subjectIds,
                        'departmentId' => $departmentIds,
                        'projectId'    => $projectIds,
                        'staffId'      => $staffIds,
                        'materialId'   => $materialIds,
                        'cashId'       => $cashIds,
                        'subjectId'    => $subjectIds
                    ]);
                    if ($isSaveMoney && empty($jieMoneys[$mxId]) && empty($daiMoneys[$mxId])) {
                        $json['warn'] = "请填写第【{$index}】行金额";
                        break;
                    } elseif ($bool !== true) {
                        $json['warn'] = $bool;
                        break;
                    }
                    $jieMoneys[$mxId] = $jieMoneys[$mxId] ?: 0;
                    $daiMoneys[$mxId] = $daiMoneys[$mxId] ?: 0;
                    if ($jieMoneys[$mxId] != 0) {
                        $direction = '借';
                    } else {
                        $direction = '贷';
                    }
                    $voucherPrice = $voucherPrices[$mxId] ?: 0;
                    $voucherNum   = $voucherNums[$mxId] ?: 0;
                    $voucherRate  = $voucherRates[$mxId] ?: 0;
                    $collection   = [
                        'voucherPrice' => voucherEditClass::formatPrice($voucherPrice),
                        'voucherRate'  => $voucherRate,//汇率
                        'voucherMoney' => $voucherRate > 0 ? round($voucherPrice * $voucherNum / $voucherRate, 2) : 0,
                    ];
                    $totalMoney   += $isSaveMoney ? ($direction == '借' ? self::yuanToCent($jieMoneys[$mxId]) : 0) : 0;
                    $material     = query('material', "id = '$materialIds[$mxId]'");
                    $mxField      = [
                        'summary'      => $summarys[$mxId],
                        'subjectId'    => $subjectIds[$mxId],
                        'subjectName'  => $subject['name'],
                        'subjectCode'  => $subject['code'],
                        'direction'    => $direction,
                        'money'        => $isSaveMoney ? $direction == '借' ? self::yuanToCent($jieMoneys[$mxId]) : self::yuanToCent($daiMoneys[$mxId]) : 0,
                        'subjectAttr'  => json_encode($collection, 320),
                        'khid'         => $khids[$mxId],
                        'supplierId'   => $supplierIds[$mxId],
                        'staffId'      => $staffIds[$mxId],
                        'projectId'    => $projectIds[$mxId],
                        'materialId'   => $materialIds[$mxId],
                        'cashId'       => $cashIds[$mxId],
                        'departmentId' => $departmentIds[$mxId],
                        'voucherNum'   => voucherEditClass::formatNum($voucherNum),
                        'currencyId'   => $currencyIds[$k] ?? '',
                        'unit'         => $material['unit'] ?: $subject['numAccountText'],
                        'rowList'      => $index
                    ];
                    $idCollection = array_filter([$mxField['khid'], $mxField['staffId'], $mxField['supplierId'], $mxField['projectId'], $mxField['materialId'], $mxField['departmentId'], $mxField['cashId']]);
                    asort($idCollection);
                    if (empty($detail['id'])) {
                        $mxField = array_merge($mxField, [
                            'id'           => $mId,
                            'coid'         => self::$coid,
                            'orderId'      => $id,
                            'idCollection' => implode(',', $idCollection)
                        ]);
                        $warn    = static::insert(array(
                            'table' => self::tableMx,
                            'field' => $mxField,
                        ));
                    } else {
                        $mxField = array_merge($mxField, [
                            'idCollection' => implode(',', $idCollection)
                        ]);
                        $warn    = static::update(array(
                            'table' => self::tableMx,
                            'field' => $mxField,
                            'where' => "id = '$detail[id]'"
                        ));
                    }
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            $warn = update(array('table' => self::table, 'field' => ['money' => $totalMoney], 'where' => "id = '$id'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
            }
            //附件
            $fileIdArr = $this->post('fileId');
            if (is_array($fileIdArr)) {
                $warn = update(array(
                    'table' => 'file',
                    'field' => ['targetId' => $id],
                    'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                ));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, "where" => "id not in ('" . implode("','", $ids) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " 【" . $field['templateName'] . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                foreach ($all['array'] as $val) {
                    fileDelete($val['src']);
                    delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                }
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['coid'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 生成模板编码
     * @return string
     */
    public static function generateTemplateNo(): string
    {
        return codeTemplateClass::generateCode(self::page, [
            'prefix' => 'T',
            'table'  => self::table,
            'field'  => 'templateNo',
            'where'  => " and coid = '" . self::$coid . "' and templateNo !='' and isTemplate = '是'",
        ], []);
    }
}
